/*
 *    Copyright 2019 The aio-socket Project
 *
 *    The aio-socket Project Licenses this file to you under the Apache License,
 *    Version 2.0 (the "License"); you may not use this file except in compliance
 *    with the License. You may obtain a copy of the License at:
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package io.task.socket.plugins.ssl.factory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class ClientSSLContextFactory implements SSLContextFactory {
	private InputStream trustInputStream;
	private String trustPassword;

	public ClientSSLContextFactory() {
	}

	public ClientSSLContextFactory(InputStream trustInputStream, String trustPassword) {
		this.trustInputStream = trustInputStream;
		this.trustPassword = trustPassword;
	}

	@Override
	public SSLContext create() throws Exception {
		TrustManager[] trustManagers;
		if (trustInputStream != null) {
			KeyStore ts = KeyStore.getInstance("JKS");
			ts.load(trustInputStream, trustPassword.toCharArray());
			TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
			tmf.init(ts);
			trustManagers = tmf.getTrustManagers();
		} else {
			trustManagers = new TrustManager[]{new X509TrustManager() {
				@Override
				public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
				}

				@Override
				public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
				}

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[0];
				}
			}};
		}
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(null, trustManagers, new SecureRandom());
		return sslContext;
	}
}
